import { Fragment, useEffect, useState } from 'react'
import { Button, Form, message } from 'antd'
import Modal from '~/components/Modal'
import { playBaseformConfigs } from '../../helper'
import { renderFormItem } from '@/components/WorkFlow/partials/FormPanel/utils/renderFormItem'
import { PlayBookService } from '@/service'

const PlayBaseModal = ({ modal, setModal, detail, setDetail, setIsRefresh }) => {

  const [form] = Form.useForm()
  const [_, setContinue] = useState(false)
  const handleContinue = () => {
    form.validateFields().then(res => {
      setModal({
        visible: false
      })
      setContinue(true)
      setDetail(detail => ({
        ...detail,
        type: 'add',
        data: res
      }))
    })
  }
  const handleSave = () => {
    form.validateFields().then(data => {
      PlayBookService.createPlay({
        wf_data: data,
        is_publish: 0
      })
        .then(res => {
          setModal({
            visible: false
          })
          message.success('创建剧本成功！')
          setIsRefresh(true)
        })
        .catch(err => {
          message.error(err)
        })
    })
  }
  const handleCancel = () => {
    setModal({
      visible: false
    })
  }
  const handleAfterClose = () => {
    setContinue(isContinue => {
      isContinue &&
        setDetail(detail => ({
          ...detail,
          visible: true
        }))
      return false
    })
    form.resetFields()
  }
  const handleEdit = () => {
    form.validateFields().then(res => {
      setModal({
        visible: false
      })
      setDetail(detail => ({
        ...detail,
        data: {
          ...detail.data,
          ...res
        }
      }))
    })
  }
  const addFooter = [
    <Button key="save" onClick={handleSave}>
      保存并关闭
    </Button>,
    <Button key="continue" type="primary" onClick={handleContinue}>
      下一步
    </Button>
  ]
  const editFooter = [
    <Button key="cancel" onClick={handleCancel}>
      取消
    </Button>,
    <Button key="save" type="primary" onClick={handleEdit}>
      保存
    </Button>
  ]

  useEffect(() => {
    if (modal.visible) {
      form.setFieldsValue(detail.data)
    }
  }, [modal, detail])
  return (
    <Modal
      visible={modal.visible}
      title="创建剧本"
      width={600}
      footer={modal.type === 'add' ? addFooter : editFooter}
      onCancel={handleCancel}
      afterClose={handleAfterClose}
      zIndex={1001}
    >
      <Form
        autoComplete="off"
        form={form}
        labelCol={{ span: 4 }}
      >
        {playBaseformConfigs.map(config => renderFormItem(config))}
      </Form>
    </Modal>
  )
}
export default PlayBaseModal
